# -*- coding: utf-8 -*-
# @Time : 2022/3/17 17:23
# @FileName: Package.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

# python 程序打包成exe  本文件必须与打包的入口文件在同一目录下
# 需要注意的是编译成pyd文件中所有import的包都需要在入口文件中再次声明一次，否则可能出现找不到某个包的现象


import os
import sys
import shutil
import re
import time
from datetime import datetime
import ctypes
from Config.Config import Version

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

# if not is_admin():
#     if sys.version_info[0] == 3:
#         ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
#         sys.exit(0)

absPath = os.path.dirname(__file__)
if os.path.exists(absPath + '/dist/Fund'):
    shutil.rmtree(absPath + '/dist/Fund')

buildFileFiles = ['/Tools/Util.py', '/Tools/Analysis.py', '/Tools/fcntlock.py', '/Tools/DBTool.py', '/Config/Config.py', '/res/resource_tool.py',
                  '/UI/LoadWidget.py', '/UI/Login/LoginDialog.py', '/UI/Login/LoginLeftWid.py', '/UI/Util/AddWidget.py',
                  '/UI/Util/SettingDialog.py', '/UI/Table/SelfSelectionTableView.py', '/UI/AccurateWidget.py', '/UI/Table/FundMainWin.py',
                  '/UI/Table/MyTableView.py', '/UI/Util/UpgradeMessage.py', '/UI/Curve/YieldRateDialog.py', '/UI/Curve/AccurateCurveDialog.py',
                  'UI/Login/StartLoadForm.py', '/UI/Util/UtilWidget.py', '/UI/Util/DaPanUnit.py', '/UI/Util/ToolBtn.py',
                  '/UI/Curve/AccChart.py', '/UI/AccountBook/AccDia.py', '/UI/AccountBook/DetailsDialog.py','/UI/AccountBook/AccountBookDialog.py',
                    '/UI/AccountBook/AccountUnit.py', '/UI/Curve/MonthDataCurve.py', '/UI/Curve/HoldingPie.py', '/Tools/FundCompany.py',
                  ]  # 需要加密的py文件，相对于本文将的相对路径

mainFile = 'Fund.py'  # 入口文件

for file in buildFileFiles:
    print('开始编译文件：{}'.format(file))
    fullPath = absPath + os.sep + file
    path, fileName = os.path.split(fullPath)

    buildStr = '# cython: language_level=3\n\nfrom distutils.core import setup\n'
    buildStr += 'from Cython.Build import cythonize\n'
    buildStr += 'setup(\n'
    buildStr += '   name="Automatically generated code.....",\n'
    buildStr += '   ext_modules=cythonize(["{}"], language_level = "3")\n'.format(fileName)
    buildStr += ')\n'

    with open(path + os.sep + 'build_pyd.py', 'w') as fp:
        fp.write(buildStr)

    os.system('activate pytorch && cd {} && python build_pyd.py build_ext --inplace'.format(path))
    os.remove(path + os.sep + 'build_pyd.py')
    os.remove(fullPath.replace('.py', '.c'))

    pydPath = fullPath.replace('.py', '.cp36-win_amd64.pyd')
    newPath = pydPath.replace('.cp36-win_amd64.pyd', '.pyd')
    if os.path.exists(newPath):
        os.remove(newPath)
    os.rename(pydPath, pydPath.replace('.cp36-win_amd64.pyd', '.pyd'))
    shutil.rmtree(path + os.sep + 'build')

    print('编译文件：{}结束'.format(file))

print('编译文件结束, 开始打包......')

resPath = absPath + os.sep + 'res'
os.system('activate pytorch && cd {} && python resource_tool.py'.format(resPath))

imgPath = 'res/Img/curve1.ico'
versionPath = 'res/file_version_info.txt'
ConfigPath = 'Config/Config.py'

# 读取当前版本信息
curVersion = Version[:8]  #前8位
curTime = datetime.strptime(curVersion, '%Y%m%d')
year = int(curTime.year)
month = int(curTime.month)
day = int(curTime.day)


# 读取更改版本文件
with open('res/file_version_info_master.txt', 'r')as fp:
    versionStr = fp.read()

versionStr = versionStr.replace('filevers=()', 'filevers=(10, {}, {}, {})'.format(year, month, day))
versionStr = versionStr.replace('prodvers=()', 'prodvers=(10, {}, {}, {})'.format(year, month, day))
versionStr = versionStr.replace('StringStruct(\'FileVersion\', \'\')', 'StringStruct(\'FileVersion\', \'10.{}.{}.{}\')'.format(year, month, day))
versionStr = versionStr.replace('StringStruct(\'ProductVersion\', \'\')])', 'StringStruct(\'ProductVersion\', \'10.{}.{}.{}\')])'.format(year, month, day))

with open(versionPath, 'w') as fp:
    fp.write(versionStr)
time.sleep(1)

os.system("cd {} && .\\venv\\Scripts\\activate.bat && pyinstaller -F -w --version-file {} -i {} {} --paths='D:\\a\Project\\MyTest\\fund\\venv\\Lib\\site-packages\\cv2'".format(absPath, versionPath , imgPath, mainFile))
# os.system('activate pytorch && cd {} && pyinstaller -F -w --version-file {} -i {} {}'.format(absPath, versionPath, imgPath, mainFile))
shutil.rmtree(absPath + os.sep + 'build')
if os.path.exists(absPath + os.sep + mainFile.replace('.py', '.spec')):
    os.remove(absPath + os.sep + mainFile.replace('.py', '.spec'))

for file in buildFileFiles:
    fullPath = absPath + os.sep + file.replace('.py', '.pyd')
    if os.path.exists(fullPath):
        os.remove(fullPath)

os.remove(versionPath)

# rename
# exePath = absPath + os.sep + 'dist/Fund.exe'
# dstPath = exePath.replace('Fund', '基金助手')
# if os.path.exists(dstPath):
#     os.remove(dstPath)
# os.rename(exePath, dstPath)

print('打包完成！')
